<?php

namespace Core\Support;

trait SingleTon
{
    private static $instance = [];

    public static function getInstance(...$args)
    {
        $cid = self::__getCoroutineCid();

        if (!isset(static::$instance[$cid])) {
            static::$instance[$cid] = new static(...$args);

            if ($cid > 0) {
                \Swoole\Coroutine::defer(function () use ($cid) {
                    unset(static::$instance[$cid]);
                });
            }
        }

        return static::$instance[$cid];
    }

    /**
     * 获取当前协程的唯一ID
     */
    public static function __getCoroutineCid()
    {
        $cid = 0;

        $call = [\Swoole\Coroutine::class, 'getCid'];
        if (is_callable($call)) {
            $cid = $call();
        }

        return $cid;
    }
}
